# uncompyle6 version 2.11.5
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.9 (default, Sep 17 2016, 20:26:04) 
# [GCC 4.9.2]
# Embedded file name: D:\project\inleader_frist_client\print_client\utils\http.py
# Compiled at: 2014-01-10 08:44:37
import urllib
import urllib2
import json
import os
import time
from setting import setting, Vfs

class UrllibHttpUtils:

    @staticmethod
    def sendGet(url, timeout=6):
        import socket
        socket.setdefaulttimeout(timeout)
        try:
            setting.logger.debug('request %s', url)
            response = urllib2.urlopen(url)
            resp_str = response.read()
            return resp_str
        except urllib2.URLError as error:
            setting.logger.exception(error.message)
        except socket.timeout as error:
            setting.logger.exception(error.message)

    @staticmethod
    def download(url, filepath):
        image = UrllibHttpUtils.sendGet(url, 30)
        if image is None:
            return
        else:
            fw = open(filepath, 'wb')
            fw.write(image)
            fw.close()
            return filepath

    @staticmethod
    def downloadPoto(url):
        ext = url.split('.')[-1]
        tmp_file_path = os.path.join(Vfs.getTempDir(), str(int(time.time())) + '.' + ext)
        return UrllibHttpUtils.download(url, tmp_file_path)

    @staticmethod
    def sendPost(url, data={}, timeout=6):
        import socket
        socket.setdefaulttimeout(timeout)
        print data
        try:
            req = urllib2.Request(url)
            setting.logger.debug('request %s', data)
            data = urllib.urlencode(data)
            opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
            response = opener.open(req, data)
            resp_str = response.read()
            opener.close()
            setting.logger.debug('response %s', resp_str)
            print resp_str
            return resp_str
        except urllib2.URLError as error:
            # setting.logger.exception(error.message)
            return
        except socket.timeout as error:
            # setting.logger.exception(error.message)
            return

        return

    @staticmethod
    def callRpc(method, parameter):
        rpc = 'http://localhost/api.php'
        if setting.config is not None:
            rpc = setting.config.get('api', 'server')
        response = UrllibHttpUtils.sendPost(rpc, {'body': json.dumps({'method': method,'parameter': parameter})})
        if response is None:
            return
        else:
            response = json.loads(response)
            if response['success']:
                return response['data']
            return